﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Web.Script.Serialization;
using System.Xml.Serialization;

namespace ShiQuan.Redis
{
    /// <summary>
    /// Json 序列化及反序列化
    /// </summary>
    public class JsonConvert
    {
        /// <summary>
        /// 将对象序列化为字符串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="t">实例</param>
        /// <returns>字符串</returns>
        public static string ToJson<T>(T t) where T : class
        {
            //BinaryFormatter formatter = new BinaryFormatter();
            //using (MemoryStream stream = new MemoryStream())
            //{                
            //    formatter.Serialize(stream, t);
            //    return System.Text.Encoding.UTF8.GetString(stream.ToArray());
            //}
            return new JavaScriptSerializer().Serialize(t);
        }
        
        /// <summary>
        /// 将字符串反序列为类型
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="s">字符串</param>
        /// <returns>对象</returns>
        public static T ToObject<T>(string s) where T : class
        {
            //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s);
            //BinaryFormatter formatter = new BinaryFormatter();
            //using (MemoryStream stream = new MemoryStream(buffer))
            //{
            //    return formatter.Deserialize(stream) as T;
            //}
            return new JavaScriptSerializer().Deserialize<T>(s);
        }

        /// <summary>
        /// 将字符串反序列为类型
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="s">字符串</param>
        /// <returns>对象</returns>
        public static T ToObject<T>(byte[] buffer) where T : class
        {
            //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s);
            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream(buffer))
            {
                return formatter.Deserialize(stream) as T;
            }
        }
    }
}
